package br.com.tenax.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateUtil {

	private static SessionFactory sessionFactory = null;
	private static Connection conexaoNativa = null;
	private static ServiceRegistry serviceRegistry;

	public static String lerPropriedadeConf(String chave) {
		Configuration cfg = new Configuration();
		cfg.configure();
		return cfg.getProperty(chave);
	}

	static {
		try {
			sessionFactory = getSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);

			sessionFactory.openSession();
			return sessionFactory;
		}
		return sessionFactory;
	}

	public static Session getSession() {
		return sessionFactory.openSession();
	}

	public static Connection getConexaoNativa() throws SQLException {
		if (conexaoNativa == null) {
			try {
				Class.forName(lerPropriedadeConf("hibernate.connection.driver_class"));
				String url = lerPropriedadeConf("hibernate.connection.url");
				String usuario = lerPropriedadeConf("hibernate.connection.username");
				String senha = lerPropriedadeConf("hibernate.connection.password");

				conexaoNativa = DriverManager
						.getConnection(url, usuario, senha);
			} catch (ClassNotFoundException e) {
				System.err.println(e);
			}
		}
		return conexaoNativa;
	}

	public static void gerarBanco() {
		Configuration cfg = new Configuration();
		cfg.configure();
		SchemaExport se = new SchemaExport(cfg);
		se.create(true, true);
	}
}